package com.ls.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.controller.logistic.model.LogisticsSmsModel;
import com.ls.entity.IsSend;
import com.ls.entity.Logistic;
import com.ls.service.IIsSendService;
import com.ls.service.ILogisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

import static com.ls.constant.SystemConstants.*;

/**
 * 物流状态轮询
 */
@Slf4j
@Component
public class LogisicStatusTask {
    @Autowired
    private ILogisticService logisticService;
    @Autowired
    private IIsSendService isSendService;

    @Scheduled(cron = "${schedule.logisic.cron}")
    private void LogisicStatusTask() {
        List<Logistic> logisticList = logisticService.list(new LambdaQueryWrapper<Logistic>()
                        .eq(Logistic::getLogisticName, "中通快递"))
                .stream()
                .filter(logistic -> {
                    IsSend isSend = isSendService.getOne(new LambdaQueryWrapper<IsSend>()
                            .eq(IsSend::getProvince, logistic.getProvince()));
                    return (logistic.getLogisticType().equals("碰碰推") && isSend.getSendPpt().equals(NUMBER_1))
                            || (logistic.getLogisticType().equals("乐信通") && isSend.getSendLxt().equals(NUMBER_1));
                })
                .collect(Collectors.toList());
        if (logisticList == null || logisticList.size() == 0 || logisticList.isEmpty()) {
            return;
        }
        logisticList.forEach(logistic -> {
            //实现中通验签并通过单号查询物流轨迹
            String result = null;
            try {
                result = logisticService.queryTrack(logistic.getLogisticNum());
                JSONObject responseJson = JSON.parseObject(result);
                if (responseJson.getBoolean("status")) {
                    JSONArray trajectories = responseJson.getJSONArray("result");
                    if (trajectories != null && !trajectories.isEmpty()) {
                        // 获取最新轨迹（scanDate最大）
                        JSONObject latestTrajectory = trajectories.stream()
                                .map(o -> (JSONObject) o)
                                .max(Comparator.comparingLong(t -> t.getLong("scanDate")))
                                .orElse(null);

                        if (latestTrajectory != null) {
                            String status = latestTrajectory.getString("scanType");
                            if (status.equals("ARRIVAL") && logistic.getReceiveSmsStatus() != SMS_STATUS_TRUE || status.equals("签收") && logistic.getReceiveSmsStatus() != SMS_STATUS_TRUE) {
                                String address = "";
                                if (status.equals("ARRIVAL")) {
                                    JSONObject scanSite = JSON.parseObject(latestTrajectory.getString("scanSite"));
                                    address = scanSite.getString("name");
                                } else {
                                    address = latestTrajectory.getString("signMan");
                                }
                                LogisticsSmsModel model = LogisticsSmsModel.builder()
                                        .logisticId(logistic.getLogisticId())
                                        .outerPhone(logistic.getPhone())
                                        .outerName(logistic.getNickname())
                                        .content(SIGN_SMS_CONTENT)
                                        .sendStatus(NUMBER_2)
                                        .name(latestTrajectory.getString("operateUser"))
                                        .address(address)
                                        .logisticStatus(status)
                                        .logisticContent(latestTrajectory.getString("desc"))
                                        .build();
                                logisticService.send(model,1);
                                //修改发送短信状态
                                logistic.setReceiveSmsStatus(SMS_STATUS_TRUE);
                            }
                            // 这里可以添加状态更新逻辑
                            if(!logistic.getLogisticStatus().equals(status)){
                                logistic.setLogisticStatus(status);
                            }
                            if (!logistic.getLogisticContent().equals(latestTrajectory.getString("desc"))){
                                logistic.setLogisticContent(latestTrajectory.getString("desc"));
                            }
                            logistic.updateById();
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

}
